package com.citywithincity.pay;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.impl.client.CloseableHttpClient;

import com.citywithincity.pay.wx.WXPayModel;
import com.citywithincity.pay.wx.WXUtil;
import com.citywithincity.utils.ConfigReader;
import com.citywithincity.utils.PathUtil;
import com.damai.plugins.impl.ApacheHttpPlugin;

public class PayFactory {
	private static Map<String, IPay> payMap = new HashMap<String, IPay>();
	@SuppressWarnings("rawtypes")
	private static  Map<String, PayAction> actions = new HashMap<String, PayAction>();

	public static final void registerPay(int businessId, int type,String channel, IPay pay) {
		payMap.put(getKey(businessId, type, channel), pay);
	}
	

	private static final String getKey(int businessId, int type,String channel){
		String key;
		if(channel==null){
			key = new StringBuilder().append(businessId).append('-').append(type).toString();
		}else{
			key = new StringBuilder().append(businessId).append('-').append(type).append('-').append(channel).toString();
		}
		return key;
	}

	public static final IPay getPay(int businessId, int type,String channel) {
		return payMap.get(getKey(businessId, type, channel));
	}
	

	

	/**
	 * 注册微信
	 * 
	 * @param payBusiness
	 * @param businessId
	 * @param wxId
	 * @param key
	 */
	public static final void registerWX(String mchId, int businessId, String channel, String wxId, String key,ApacheHttpPlugin plugin) {
		try{
			CloseableHttpClient client = WXUtil.createHttpClient(getP12(mchId), mchId);
			if(client!=null && plugin!=null){
				plugin.register(client);
			}
			PayFactory.registerPay(businessId, PayType.PayType_WX,channel,
					new WXPayModel(client, wxId, key, mchId,channel));
			
		}catch(Exception e){
			if(e instanceof RuntimeException){
				throw (RuntimeException)e;
			}
			throw new RuntimeException(e);
		}
		
	}

	private static InputStream getP12(String payBusiness) throws Exception  {
		
		return PathUtil.getConfigInputStream(ConfigReader.class, payBusiness+".p12");
	}


	public static void registerAction(int businessId,  PayAction<?, ?, ?> payAction) {
		actions.put(String.valueOf(businessId), payAction);
	}


	
	@SuppressWarnings("unchecked")
	public static <T extends PayAction<?, ?, ?>> T getPayAction(int businessId) {
		return (T) actions.get(String.valueOf(businessId));
	}

	

	private static String notifyUrl;

	public static void setNotifyUrl(String url) {
		notifyUrl = url;
	}

	public static String getNotifyUrl() {
		return notifyUrl;
	}
}
